#include "gd32f30x.h"
#include "stdio.h"
#include "stdint.h"
#include "DevicesDelay.h"
#include "DevicesUart.h"
#include "DevicesRS485.h"


void vRS485LogInit(void)
{
    /* enable the GPIO clock */
    rcu_periph_clock_enable(RCU_GPIOD);

    /* configure key pin as input */
    gpio_init(RS485_LOG_GPIO_Port, GPIO_MODE_OUT_PP, GPIO_OSPEED_10MHZ, RS485_LOG_Pin);

    RS485_LOG_MODE_RECEIVE();

    vUart0Init();
}

void vRS485BusInit(void)
{
    /* enable the GPIO clock */
    rcu_periph_clock_enable(RCU_GPIOE);

    /* configure key pin as input */
    gpio_init(RS485_BUS_GPIO_Port, GPIO_MODE_OUT_PP, GPIO_OSPEED_10MHZ, RS485_BUS_Pin);

    RS485_BUS_MODE_RECEIVE();

    vUart2Init();
}

int8_t cRS485xSendDatas(uint32_t uiChannel, void *pvBuff, int32_t iLength)
{
    if((pvBuff == NULL) || (iLength < 1))
        return 1;

    if(uiChannel == UART_LOG)
    {
        /* 设置为发送模式 */
        RS485_LOG_MODE_SEND();

        /* RS485协议标准推荐在设置为发送模式后，增加1个bit的延时 */
        vDelayUs(1000000.0f / 115200.0f);

        /* 发送数据 */
        vUartDMASendDatas(uiChannel, pvBuff, iLength);

        /* RS485协议标准推荐在设置为接收模式前，增加1个bit的延时 */
        vDelayUs(1000000.0f / 115200.0f);

        /* 设置为接收模式 */
        RS485_LOG_MODE_RECEIVE();
    }
    else if(uiChannel == UART_BUS)
    {
        /* 设置为发送模式 */
        RS485_BUS_MODE_SEND();

        /* RS485协议标准推荐在设置为发送模式后，增加1个bit的延时 */
        vDelayUs(1000000.0f / 115200.0f);

        /* 发送数据 */
        vUartDMASendDatas(uiChannel, pvBuff, iLength);

        /* RS485协议标准推荐在设置为接收模式前，增加1个bit的延时 */
        vDelayUs(1000000.0f / 115200.0f);

        /* 设置为接收模式 */
        RS485_BUS_MODE_RECEIVE();
    }

    return 0;
}

int8_t cRS485xReceiveDatas(uint32_t uiChannel, void *pvBuff, int32_t iLength)
{
    return cUartReceiveDatas(uiChannel, pvBuff, iLength);
}

int32_t iRS485xReceiveAllDatas(uint32_t uiChannel, void *pvBuff, int32_t iLengthLimit)
{
    return iUartReceiveAllDatas(uiChannel, pvBuff, iLengthLimit);
}

int8_t cRS485xReceiveByte(uint32_t uiChannel, uint8_t *pucBuff)
{
    return cUartReceiveDatas(uiChannel, pucBuff, 1);
}

int32_t iRS485xReceiveLengthGet(uint32_t uiChannel)
{
    return iUartReceiveLengthGet(uiChannel);
}

int8_t cRS485xReceiveClear(uint32_t uiChannel)
{
    return cUartReceiveClear(uiChannel);
}
